package com.xlx.openLink.controller;

import com.alibaba.fastjson.JSON;
import com.xlx.openLink.base.BaseDateMessage;
import com.xlx.openLink.base.BaseMessage;
import com.xlx.openLink.base.ThreadRunTimeExcption;
import com.xlx.openLink.conf.MailBean;
import com.xlx.openLink.conf.MysqlProperties;
import com.xlx.openLink.entity.pojo.Backup;
import com.xlx.openLink.entity.pojo.Manager;
import com.xlx.openLink.entity.pojo.Sys;
import com.xlx.openLink.enums.ResultCodeEnum;
import com.xlx.openLink.enums.SysParamsEnums;
import com.xlx.openLink.service.ManagerService;
import com.xlx.openLink.service.SysService;
import com.xlx.openLink.uitls.AssertUtils;
import com.xlx.openLink.uitls.Commuitls;
import com.xlx.openLink.uitls.RemoteShellExecutor;
import com.xlx.openLink.vo.AlarmIds;
import com.xlx.openLink.vo.MysqlInfo;
import com.xlx.openLink.vo.RequestManagerLst;
import com.xlx.openLink.vo.SshVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@Controller
@RequestMapping("/manager")
public class ManagerController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private MysqlProperties mysqlProperties;

    @Autowired
    private SysService sysService;

    private static final Logger LOGGER = LoggerFactory.getLogger(ManagerController.class);


    /**
     * 用户登录
     *
     * @param manager
     * @return
     */
    @PostMapping(value = "/login")
    @ResponseBody
    public BaseDateMessage login(@RequestBody Manager manager, HttpServletRequest request) {
        BaseDateMessage baseDateMessage = new BaseDateMessage();
        log.info("用户{}登录-----", manager.getmName());
        try {
            Manager ret = managerService.login(manager, request);
            AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.DATA_NOT_EXIST), ret);
            baseDateMessage.setData(ret);
            baseDateMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } catch (ThreadRunTimeExcption e) {
            log.info("处理错误");
            baseDateMessage.buildFail(e.getResultCodeEnum());
        } catch (Exception e) {
            log.info("服务器错误");
            baseDateMessage.buildFail(ResultCodeEnum.SERVER_ERROR);
        }
        return baseDateMessage;
    }

    /**
     * 添加用户
     *
     * @param manager
     * @return
     */
    @PostMapping(value = "/add")
    @ResponseBody
    public BaseMessage add(@RequestBody Manager manager) {
        BaseMessage baseMessage = new BaseMessage();
        try {
            managerService.addManager(manager);
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } catch (ThreadRunTimeExcption e) {
            log.info("处理错误");
            baseMessage.buildFail(e.getResultCodeEnum());
        } catch (Exception e) {
            log.info("服务器错误" + e.getMessage());
            baseMessage.buildFail(ResultCodeEnum.SERVER_ERROR);
        }
        return baseMessage;
    }

    /**
     * 添加用户
     *
     * @param pkGuid
     * @return
     */
    @GetMapping(value = "/del")
    @ResponseBody
    public BaseMessage del(@RequestParam(value = "pkGuid") String pkGuid) {
        BaseMessage baseMessage = new BaseMessage();
        try {
            managerService.delManager(pkGuid);
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } catch (ThreadRunTimeExcption e) {
            LOGGER.info("处理错误");
            baseMessage.buildFail(e.getResultCodeEnum());
        } catch (Exception e) {
            LOGGER.info("服务器错误");
            baseMessage.buildFail(ResultCodeEnum.SERVER_ERROR);
        }
        return baseMessage;
    }

    /**
     * 更新用户
     *
     * @param manager
     * @return
     */
    @PostMapping(value = "/update")
    @ResponseBody
    public BaseMessage update(@RequestBody Manager manager) {
        BaseMessage baseMessage = new BaseMessage();
        try {

            managerService.update(manager);
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } catch (ThreadRunTimeExcption e) {
            LOGGER.info("处理错误");
            baseMessage.buildFail(e.getResultCodeEnum());
        } catch (Exception e) {
            LOGGER.info("服务器错误");
            baseMessage.buildFail(ResultCodeEnum.SERVER_ERROR);
        }
        return baseMessage;
    }

    @ApiOperation(value = "分页查询", notes = "分页查询")
    @ApiImplicitParam(name = "request", value = "分页请求参数", required = true, dataType = "RequestManagerLst")
    @PostMapping("/listByPage")
    @ResponseBody
    public BaseDateMessage listByPage(@RequestBody RequestManagerLst request) {

        BaseDateMessage baseDateMessage = new BaseDateMessage();
        try {
            baseDateMessage.setData(managerService.listByPage(request));
            baseDateMessage.buildSuccess(ResultCodeEnum.SUCCESS);
            baseDateMessage.setMsg("获取成功");
        } catch (ThreadRunTimeExcption excption) {
            baseDateMessage.buildSuccess(excption.getResultCodeEnum());
        } catch (Exception e) {
            log.info(e.getMessage());
            baseDateMessage.buildFail(ResultCodeEnum.FAIL);
            baseDateMessage.setMsg("获取失败");
        }
        return baseDateMessage;
    }

    @GetMapping(value = "/select")
    @ResponseBody
    public BaseMessage select(@RequestParam(value = "pkGuid") String pkGuid) {
        BaseDateMessage baseMessage = new BaseDateMessage();
        try {
            baseMessage.setData(managerService.select(pkGuid));
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } catch (ThreadRunTimeExcption e) {
            log.info("查询错误");
            baseMessage.buildFail(e.getResultCodeEnum());
        } catch (Exception e) {
            log.info("服务器错误");
            baseMessage.buildFail(ResultCodeEnum.SERVER_ERROR);
        }
        return baseMessage;
    }

    @PostMapping(value = "/delList")
    @ResponseBody
    public BaseMessage delList(@RequestBody AlarmIds ids) {
        BaseDateMessage baseMessage = new BaseDateMessage();
        try {
            baseMessage.setData(managerService.delList(ids));
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } catch (ThreadRunTimeExcption e) {
            log.info("删除成功");
            baseMessage.buildFail(e.getResultCodeEnum());
        } catch (Exception e) {
            log.info("服务器错误");
            baseMessage.buildFail(ResultCodeEnum.SERVER_ERROR);
        }
        return baseMessage;
    }


    /**
     * 重启系统
     */
    @ResponseBody
    @PostMapping(value = "/restart")
    public BaseMessage restart() {
        //系统重启
        BaseDateMessage baseMessage = new BaseDateMessage();
        try {
            Sys sys = sysService.selctByCode(SysParamsEnums.SYS_SSH.getCode());
            if (sys == null) {
                baseMessage.setMsg("未找到ssh连接信息！请在系统管理进行设置");
                baseMessage.buildFail(ResultCodeEnum.FAIL);
            } else {
                SshVo sshVo = (SshVo) JSON.parseObject(sys.getSysParam(), SshVo.class);
                RemoteShellExecutor executor = new RemoteShellExecutor(sshVo.getIp(), sshVo.getName(), sshVo.getPwd(), sshVo.getPort());
                executor.exec("reboot");
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return baseMessage;
    }

    /**
     * 操作ssh
     *
     * @param sshVo
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/optionSSH")
    public BaseMessage optionSSH(@RequestBody SshVo sshVo) {
        BaseDateMessage baseMessage = new BaseDateMessage();
        try {
            int count = sysService.optionSSH(SysParamsEnums.SYS_SSH.getCode(), sshVo);
            if (count == 1) {
                baseMessage.setMsg("操作成功");
                baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
            } else {
                baseMessage.setMsg("操作失败");
                baseMessage.buildSuccess(ResultCodeEnum.FAIL);
            }
        } catch (ThreadRunTimeExcption e) {
            baseMessage.setMsg(e.getMessage());
            baseMessage.buildSuccess(ResultCodeEnum.FAIL);
        }
        return baseMessage;
    }


    /**
     * 操作mysql
     *
     * @param mysqlInfo
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/optionMysql")
    public BaseMessage optionMysql(@RequestBody MysqlInfo mysqlInfo) {
        BaseDateMessage baseMessage = new BaseDateMessage();
        int count = sysService.optionMysqlInfo(SysParamsEnums.MYSQL_INFO.getCode(), mysqlInfo);
        if (count == 1) {
            baseMessage.setMsg("操作成功");
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } else {
            baseMessage.setMsg("操作失败");
            baseMessage.buildSuccess(ResultCodeEnum.FAIL);
        }
        return baseMessage;
    }

    @ResponseBody
    @PostMapping(value = "/optionMailBean")
    public BaseMessage optionMailBean(@RequestBody MailBean mailBean) {
        BaseDateMessage baseMessage = new BaseDateMessage();
        int count = sysService.optionMailBean(SysParamsEnums.SYS_MAIL.getCode(), mailBean);
        if (count == 1) {
            baseMessage.setMsg("操作成功");
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } else {
            baseMessage.setMsg("操作失败");
            baseMessage.buildSuccess(ResultCodeEnum.FAIL);
        }
        return baseMessage;
    }



    /**
     * 手动备份数据库
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @GetMapping(value = "/backup")
    public void backups(HttpServletRequest request,
                        HttpServletResponse response) {
        BaseDateMessage baseMessage = new BaseDateMessage();
        try {
            Backup backup = managerService.backups();
            this.setResponseHeader(response, backup.getBakName());
            OutputStream os = response.getOutputStream();
            File file = new File(backup.getBakPath());
            InputStream inputStream = new FileInputStream(file);
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
            os.close();
            inputStream.close();
            baseMessage.buildFail(ResultCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.info("执行备份失败");
            baseMessage.buildFail(ResultCodeEnum.FAIL);
            e.printStackTrace();
        }

    }

    /**
     * 备份还原
     *
     * @param pkGuid
     */
    @ResponseBody
    @GetMapping(value = "/restore")
    public BaseDateMessage backups(@RequestParam(value = "pkGuid") String pkGuid) {
        BaseDateMessage baseMessage = new BaseDateMessage();
        try {
            managerService.restore(pkGuid);
            baseMessage.setMsg("还原成功");
            baseMessage.buildSuccess(ResultCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.info("执行还原失败");
            baseMessage.setMsg("执行还原失败");
            baseMessage.buildFail(ResultCodeEnum.FAIL);
            e.printStackTrace();
        }
        return baseMessage;

    }


    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


}
